package cn.harry.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author harry
 * @公众号 Harry技术
 * Spring Boot 3 集成 Spring Security（2） 授权: https://mp.weixin.qq.com/s/HzzcYIQLnch_7r7wdUarew
 */
@Slf4j
@RestController
public class SecuredController {

    /**
     * 使用 `@Secured`注解时，需要再 SecurityConfig 文件中添加`@EnableMethodSecurity(securedEnabled = true) // 开启方法级别的权限控制`
     * 访问 /secured 需要有 ROLE_USER 权限
     */
    @GetMapping(value = "/secured")
    @Secured("ROLE_USER")
    public User hello() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("当前登录的用户信息：{}", user.toString());
        return user;
    }
}
